import { reqUserLogin, reqUserInfo, reqUserLogout} from "@/api"

const state = {
    token:'',
    userInfo:{}
}
const mutations = {
    SET_TOKEN(state,token){
       state.token = token
    },
    SET_USERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    RESET_TOKEN(state){
        state.token = ''
    },
    RESET_USERINFO(state){
        state.userInfo = {}
    }
}
const actions = {
    async userLogin({commit},userInfo){
        const result = await reqUserLogin(userInfo)
        if(result.code === 200){
            commit('SET_TOKEN',result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },

    async getUserInfo({commit}){
        const result = await reqUserInfo()
        if(result.code === 200){
          commit('SET_USERINFO',result.data)
          return 'ok'
        }else{
          return Promise.reject(new Error('failed'))
        }
    },

    clearToken({commit}){
        commit('RESET_TOKEN')
    },

    async userLogout({commit,dispatch}){
        const result = await reqUserLogout()
        if(result.code === 200){
          commit('RESET_USERINFO') 
          dispatch('clearToken')
          return 'ok'
        }else{
          return Promise.reject(new Error('failed'))
        }
    },
}
const getters ={}

export default {
    state,
    mutations,
    actions,
    getters
}